const express = require('express')
const router = express.Router()
const User = require('../../models/User')

let responseData 


/** 后台查询用户列表接口
 */
router.get('/', function(req, res, next) {
	responseData = {
		resultCode: 0,
		resultMsg: 'success',
		data: {}
	}
	// 分页
	let limit = req.query.pageSize || 10
	let currentPage = req.query.currentPage || 1
	let skip = (currentPage- 1) * 10 || 0
	// 算出总条数
	User.count().then(function(totalNumber) {
		// 页数
		let totalPages = Math.ceil(totalNumber/limit)

		User.find().limit(limit).skip(skip).then(function(userList) {
			responseData.data['list'] = userList
			responseData.data['totalNumber'] = totalNumber
			responseData.data['totalPages'] = totalPages
			responseData.data['currentPage'] = currentPage
			responseData.data[' pageSize'] = limit
			res.json(responseData)
		})
	})

})


/** 后台修改用户接口
*/
router.post('/update', function(req, res, next) {
	responseData = {
		resultCode: 0,
		resultMsg: 'success',
		data: {}
	}
	console.log(req.body)
	let { _id, username, password, isAdmin } = req.body

	if(!_id) {
		responseData.resultCode = 1
		responseData.resultMsg = '没有传必要参数'
		res.json(responseData)
	}
	// 判断用户名是否重复
	User.findOne({
		username: username
	}).then(UserInfo => {
		if(UserInfo) {
			responseData.resultCode = 1
			responseData.resultMsg = '用户名已经存在'
			res.json(responseData)
		}

		if(username) {
			User.update({
				_id: _id
			}, {
				username: username
			}).then((affectLine) => {
				res.json(responseData)
			})
		}
		if(password) {
			User.update({
				_id: _id
			}, {
				password: password
			}).then((affectLine) => {
				res.json(responseData)
			})
		}
		if(isAdmin) {
			User.update({
				_id: _id
			}, {
				isAdmin: isAdmin
			}).then((affectLine) => {
				res.json(responseData)
			})
		}
	})
})


/** 新增用户
*/
router.post('/add', function(req, res, next) {
	responseData = {
		resultCode: 0,
		resultMsg: 'success',
		data: {}
	}
	let { username, password, isAdmin } = req.body
	if(!username || !password) {
		responseData.resultCode = 1
		responseData.resultMsg = '用户名或者密码不能为空'
		res.json(responseData)
		return
	}

	User.findOne({
		username: username
	}).then(UserInfo => {
		if(UserInfo) {
			responseData.resultCode = 1
			responseData.resultMsg = '用户名已经存在'
			res.json(responseData)
			return
		}
		let user = new User({
			username,
			password,
			isAdmin: isAdmin == true ? true : false
		})

		user.save().then(UserInfo => {
			res.json(responseData)
		})
	})
})


router.get('/delete', function(req, res, next) {
	responseData = {
		resultCode: 0,
		resultMsg: 'success',
		data: {}
	}
	let _id = req.query._id
	User.findOne({
		_id: _id
	}).then(UserInfo => {
		if(!UserInfo) {
			responseData.resultCode = 1
			responseData.resultMsg = '用户不存在'
			res.json(responseData)
		}
		User.remove({
			_id:_id
		}).then(function(affectLine) {
			res.json(responseData)
		})
	})
})



module.exports = router